<template>
  <el-form ref="userAddEditRef"
    :model="form"
    :rules="rules"
    label-width="120px">
    <el-row class="mb20">
      <el-col :span="12">
        <el-form-item label="所属区划">
          <el-input v-model="form.adName"
            disabled />
        </el-form-item>
      </el-col>
      <template v-if="isUnit">
        <el-col :span="12">
          <el-form-item label="所属单位">
            <el-input v-model="treeParams.agName"
              disabled />
          </el-form-item>
        </el-col>
      </template>
    </el-row>
    <el-row class="mb20">
      <el-col :span="12">
        <el-form-item label="用户编码"
          prop="code">
          <el-input v-model="form.code"
            placeholder="请输入用户编码"
            :disabled="isEdit" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="用户名称"
          prop="name">
          <el-input v-model="form.name"
            placeholder="请输入用户名称" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row class="mb20">
      <el-col :span="12">
        <el-form-item label="用户类型"
          prop="usertype">
          <rk-select style="width: 100%"
            v-model="form.usertype"
            :is-search="false"
            :show-code="false"
            placeholder="请选择用户类型"
            @change="handleChange"
            :options="userTypeOptions">
          </rk-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态"
          prop="status">
          <rk-select style="width: 100%"
            v-model="form.status"
            :is-search="false"
            placeholder="请选择状态"
            :options="toArray(COMMON_STOP_OPEN_MT_ENUMS)">
          </rk-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row class="mb20">
      <el-col :span="12">
        <el-form-item label="用户角色"
          prop="roleGuid">
          <rk-select style="width: 100%;"
            v-model="form.roleGuid"
            :server="getRoleSelect"
            :label-config="{
                                   label:'roleName',
                                   value:'roleCode'
                               }"
            placeholder="请选择用户角色">
          </rk-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="数据权限">
          <rk-tree-select v-model="form.upAgencyId"
            :server="loadAuthTree"
            :props='{ label: "name", value: "id", children: "children"}'>
          </rk-tree-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row class="mb20">
      <template v-if="!isUnit">
        <el-col :span="12"
          class="mb20">
          <el-form-item label="归口处室">
            <rk-select style="width: 100%"
              v-model="form.division"
              :labelConfig=' { value: "id", label: "name" }'
              placeholder="请选择归口处室"
              dist="DSY_V_ELE_FINDEP">
            </rk-select>
          </el-form-item>
        </el-col>
      </template>
      <template v-if="isDivsion">
        <el-col :span="12">
          <el-form-item label="管辖单位">
            <el-tree-select ref="treeSelectRef"
              v-model="form.roleAgs"
              multiple
              node-key="id"
              collapse-tags
              :props="treeSelectProps"
              placeholder="请选择管辖单位"
              style="width: 100%"
              :data="agencyTreeData"
              :render-after-expand="false"
              show-checkbox>
            </el-tree-select>
          </el-form-item>
        </el-col>
      </template>
      <el-col :span="12">
        <el-form-item label="手机号码"
          prop="phoneNumber">
          <el-input style="width: 100%;"
            v-model="form.phoneNumber"
            :min="0"
            placeholder="请输入手机号码" />
        </el-form-item>
      </el-col>
      <el-col :span="12"
        class="mb20">
        <el-form-item label="身份证号码"
          prop="idCode">
          <el-input v-model="form.idCode"
            placeholder="请输入身份证号码" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="职务">
          <el-input v-model="form.job"
            placeholder="请输入职务" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="电子邮件"
          prop="email">
          <el-input v-model="form.email"
            placeholder="请输入电子邮件" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup>
/**
 *
 */
import XEUtils from 'xe-utils'
import { inject, onMounted, reactive, ref, watch } from "vue";
import { USER_TYPE } from "@/enums/enums-system.js";
import { EMAIL_REG, ID_CODE_REG, PHONE_NUMBER_REG } from "@/common/cons-regular.js";
import { COMMON_STOP_OPEN_ENUMS, COMMON_STOP_OPEN_MT_ENUMS, toArray } from "@/enums/enums-common.js";
import { useTreeApi, useRoleApi, useUserApi } from "@/api/index.js";

const { getAdRegin, getPubAgencyTree } = useTreeApi();
const { getUserRoleAgInfo } = useUserApi();
const { getRoleInfo } = useRoleApi();
// import FormValidateTip from '@/components/form/FormValidateTip.vue'
const userAddEditRef = ref(null)
const treeSelectRef = ref(null)

const treeSelectProps = {
  label: (data, node) => {
    return `${data.code} ${data.name}`
  },
  children: 'children'
}

const form = reactive({
  agency: "",
  code: "",
  division: "",
  email: "",
  guid: "",
  idCode: "",
  job: "",
  name: "",
  roleAgs: void 0,
  phoneNumber: "",
  province: "",
  roleGuid: "",
  status: "1",
  usertype: 0,
  upAgencyId: "",
})
const props = defineProps({
  userModel: {
    type: Object,
    default: {}
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})


const userTypeOptions = ref([])
// 是否是包含处室
const isDivsion = ref(false)
// 判断是否选中单位或区划
const isUnit = ref(false)
const treeParams = inject('treeParams')
const agencyTreeData = ref([])
watch(isDivsion, () => {
  if (isDivsion.value) {
    loadAgencyTree()
  }
})

const rules = reactive({
  code: [
    { required: true, message: '请输入用户编码', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
  ],
  usertype: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  roleGuid: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
  phoneNumber: [{ pattern: PHONE_NUMBER_REG, message: '手机号不符合规范！', trigger: 'blur' },],
  idCode: [{ pattern: ID_CODE_REG, message: '身份证号不符合规范！', trigger: 'blur' },],
  email: [{ pattern: EMAIL_REG, message: '电子邮件不符合规范！', trigger: 'blur' },],
})
onMounted(() => {
  if (props.isEdit) {
    Object.assign(form, props.userModel,
      {
        roleGuid: props.userModel.roleCode,
      })
  } else {
    Object.assign(form, props.userModel,
      {
        upAgencyId: treeParams.agId || treeParams.adId,
        province: treeParams.adCode,
        agency: treeParams.agId,
        roleGuid: props.userModel.roleCode,
        adName: treeParams.adName
      })
  }
  handleUserType()
})
const loadAuthTree = async () => {

  const resp = await getAdRegin({
    adCode: props.isEdit ? props.userModel.province : treeParams.adCode,
    agId: treeParams.agId
  })
  if (resp.code === 200) {
    return resp.data
  }
}
const loadAgencyTree = async () => {
  const res = await getUserRoleAgInfo(form.guid)
  if (res.code === 200) {
    if (res.data && res.data.length > 0) {
      form.roleAgs = res.data.map(item => {
        return item.agId
      })
    } else {
      form.roleAgs = []
    }
  }
  const resp = await getPubAgencyTree({ adCode: treeParams.adCode })
  if (resp.code === 200) {
    if (resp.data && resp.data.length > 0) {
      agencyTreeData.value = resp.data
    }
  }
}
const handleUserType = () => {
  if (treeParams.agId) {
    isUnit.value = true
    userTypeOptions.value = toArray(USER_TYPE).filter(item => {
      return (item.value === 0 || item.value === 2)
    })
    if (!form.usertype) {
      form.usertype = 0
    }
    isDivsion.value = false
    return
  }
  isUnit.value = false
  if (form.usertype === 5) {
    isDivsion.value = true
  }
  userTypeOptions.value = toArray(USER_TYPE).filter(item => {
    return (item.value === 1 || item.value === 5)
  })
  if (!form.usertype) {
    form.usertype = 1
  }
}

/** 修改用户类型 */
const handleChange = ([val]) => {
  const { value } = val
  if (value == 0 || value == 2) {
    // form.upAgencyId = treeParams.agId
    isDivsion.value = false
  } else {
    if (value == 5) {
      isDivsion.value = true
    } else {
      isDivsion.value = false
    }
    // form.upAgencyId = treeParams.adId
  }
}


const getRoleSelect = async () => {
  const resp = await getRoleInfo({})
  if (resp.code === 200) {
    return resp.data
  }
  return []
}
/** 获取表单数据 */
const getFormData = () => {
  let resultData = {}
  Object.assign(resultData, form)
  if (resultData.roleAgs && resultData.roleAgs instanceof Array) {
    resultData.roleAgs = resultData.roleAgs.join(",")
  }
  if (!isUnit) { // 单位
    resultData.agCode = void 0
    resultData.agId = void 0
  }
  return resultData
}
/** 表单校验 */
const validateForm = async () => {
  if (!userAddEditRef.value) return false
  return await userAddEditRef.value.validate()

}
defineExpose({
  getFormData,
  validateForm
})
</script>
<style lang="scss" scoped>
</style>
